Custom Elements
HTMLに独自のタグを作れる
初めて見た頃はだいぶ違和感あったが、その後React(JSX)とか書いてるうちにその感覚は薄れた
HTMLElementを継承したclassを作って、customElements.define()で呼ぶ
code:js
class HogePiyo extends HTMLElement {
constructor() {
super();
this.innerHTML = <div>custom hoge</div>;
}
}
window.customElements.define('hoge-piyo', HogePiyo);
code:html
<hoge-piyo></hoge-piyo>
MDN Web見てたらこういう無名クラスを使った定義の書き方されててなるほどだった
code:js
customElements.define('my-paragraph',
class extends HTMLElement {
constructor() {
super();
}
})
https://developer.mozilla.org/ja/docs/Web/Web_Components/Using_templates_and_slots
さらにtemplate(HTML TemplatesやShadow DOMなどと組み合わせるとこんな感じ
code:js
const tmpl = document.createElement('template');
tmpl.innerHTML = `
<style>
:host {}
</style>
<div>
<slot></slot>
</div>
`;
customElements.define('my-paragraph',
class extends HTMLElement {
constructor() {
super();
const shadowRoot = this.attachShadow({mode: 'open'});
shadowRoot.appendChild(tmpl.content.cloneNode(true));
}
}
)
https://codepen.io/zakuni/pen/gOxBRBy
属性(attributes)とかプロパティ(properties)とか
attributesは常にstring。htmlからも値を設定できる
attributeChangedCallback(name, oldValue, newValue)が発火する
propertiesはJSのproperties
booleanの属性はちょっと特殊
htmlのdisabled属性みたいなもので、書かれているか否かでtrueかfalseになる
disabled=falseとかdisabled=''とか書いたとて、disabledがあるかどうかなので、trueになる
先述の通りattributeはそもそもstringなので、boolean attributeにしたかったらちょっと工夫する必要アリ
hasAttributesで判定するとか、falseに切り替えるためにはremoveAttributesを使うとか